package com.spic.system.service.impl;

import com.spic.system.domain.AppVersion;
import com.spic.system.mapper.AppVersionMapper;
import com.spic.system.service.AppVersionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * app版本
 */
@Service
public class AppVersionServiceImpl  implements AppVersionService {

    @Autowired
    private AppVersionMapper appVersionMapper;
    /**
     * 获取最新的app版本信息
     * @return
     */
    @Override
    public AppVersion getAppVersion(String version) {
        AppVersion appVersion = appVersionMapper.getAppVersion();
        String newVersion = appVersion.getVersion();
        appVersion.setIsChange(this.compareVersion(newVersion,version));
        return appVersion;
    }

    /**
     * 比较两个版本号的大小，如果version1大于version2，返回值为1，等于为0，小于为-1
     *  例如：1.2.4和1.1.100比较大小，应是前者大于后者！
     * @param version1 第一个版本号
     * @param version2 目标版本号
     * @return 结果
     */
    public Integer compareVersion(String version1, String version2) {
        try {
            if (version1 == null || version2 == null) {
                throw new IllegalArgumentException("Bad version number");
            }
            String[] versionArray1 = version1.split("\\.");
            String[] versionArray2 = version2.split("\\.");
            if (versionArray1.length != 3 || versionArray2.length != 3) {
                throw new IllegalArgumentException("Bad version number");
            }
            // 逐段比较版本号，先比较第一位
            Integer result = null;
            for (int i = 0; i < 3; i++) {
                Integer v1 = Integer.parseInt(versionArray1[i]);
                Integer v2 = Integer.parseInt(versionArray2[i]);
                result = Integer.compare(v1 - v2, 0);
                if (result != 0) {
                    break;
                }
            }
            return result;
        } catch (Exception ex) {
            return -2;
        }
    }
}
